package ml.coursedesign.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ml.coursedesign.common.lang.Result;
import ml.coursedesign.common.lang.StatusCode;
import ml.coursedesign.entity.Course;
import ml.coursedesign.entity.CourseClass;
import ml.coursedesign.service.CourseClassService;
import ml.coursedesign.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 前端控制器：课程
 *
 * @author likeqc.top
 * @since 2021-04-27
 */
@RestController
@RequestMapping("/course")
public class CourseController {
  // TODO: 权限验证，都还没有写

  @Autowired private CourseService courseService;
  @Autowired private CourseClassService courseClassService;

  /**
   * 根据id删除课程
   *
   * @param id 课程id
   * @return
   */
  @DeleteMapping("/{id}")
  public Result remove(@PathVariable Integer id) {
    courseService.removeById(id);
    return Result.succ(null);
  }

  /**
   * 新增或修改课程
   *
   * @param course 课程实体
   * @return
   */
  //  @PostMapping("/edit")
  @PostMapping("/edit")
  public Result edit(@RequestBody Course course) {
    // TODO: 权限验证，管理员才有资格编辑课程信息
    String msg = null;
    if (course.getId() == null || courseService.getById(course.getId()) == null) {
      // 新增
      courseService.save(course);
      msg = "新增成功";
    } else {
      // 修改
      courseService.updateById(course);
      msg = "修改成功";
    }
    return Result.succ(StatusCode.OK, msg, course);
  }

  /**
   * 分页查询，仅查询课程信息列表
   *
   * @param currentPage 要查询的页数，默认1
   * @param size 每页大小，默认5
   * @return
   */
  @GetMapping("")
  public Result list(
      @RequestParam(defaultValue = "1") Integer currentPage,
      @RequestParam(defaultValue = "5") Integer size) {
    Page<Course> page = new Page<Course>(currentPage, size);
    // IPage<Course> pageData = courseService.page(page, new QueryWrapper<Course>());
    IPage<Map> pageData = courseService.getList(page);
    return Result.succ(pageData);
  }

  /**
   * 查询某一门课程下所有班级
   *
   * @param id 课程id
   * @param currentPage 当前页，默认1
   * @param size 分页大小，默认50
   * @return
   */
  @GetMapping("/{id}")
  public Result list(
      @PathVariable Integer id,
      @RequestParam(defaultValue = "1") Integer currentPage,
      @RequestParam(defaultValue = "50") Integer size) {
    Page<CourseClass> page = new Page<CourseClass>(currentPage, size);
    // IPage<CourseClass> pageData =
    //     courseClassService.page(page, new QueryWrapper<CourseClass>().eq("course_id", id));
    // return Result.succ(pageData);
  
    IPage<Map> pageData = courseClassService.getListByCourseId(page, id);
    System.out.println(pageData);
    return Result.succ(pageData);
  }
}
